import 'package:flutter/material.dart';

class AnimatedUnderlineTabBar extends StatefulWidget {
  final List<String> tabs;
  final int selectedIndex;
  final ValueChanged<int> onTabTap;
  final double lineWidth;
  final double lineHeight;
  final double tabSpacing;
  final Color selectedColor;
  final Color unselectedColor;
  final Color lineColor;
  final TextStyle? selectedTextStyle;
  final TextStyle? unselectedTextStyle;
  final double verticalSpacing;
  final double lineRadius;
  final Duration lineDuration;
  final Curve lineCurve;
  final EdgeInsetsGeometry padding; // 新增：整体内边距

  const AnimatedUnderlineTabBar({
    super.key,
    required this.tabs,
    required this.selectedIndex,
    required this.onTabTap,
    this.lineWidth = 32,
    this.lineHeight = 4,
    this.tabSpacing = 30,
    this.selectedColor = Colors.white,
    this.unselectedColor = Colors.white70,
    this.lineColor = Colors.white,
    this.selectedTextStyle,
    this.unselectedTextStyle,
    this.verticalSpacing = 8,
    this.lineRadius = 2,
    this.lineDuration = const Duration(milliseconds: 300),
    this.lineCurve = Curves.ease,
    this.padding =
        const EdgeInsets.symmetric(horizontal: 0, vertical: 0), // 默认无内边距
  });

  @override
  State<AnimatedUnderlineTabBar> createState() =>
      _AnimatedUnderlineTabBarState();
}

class _AnimatedUnderlineTabBarState extends State<AnimatedUnderlineTabBar> {
  late List<GlobalKey> textKeys;
  double lineLeft = 0;

  @override
  void initState() {
    super.initState();
    textKeys = List.generate(widget.tabs.length, (_) => GlobalKey());
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _updateLine();
    });
  }

  @override
  void didUpdateWidget(covariant AnimatedUnderlineTabBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _updateLine();
    });
  }

  void _updateLine() {
    double left = 0;
    for (int i = 0; i < widget.selectedIndex; i++) {
      final RenderBox? box =
          textKeys[i].currentContext?.findRenderObject() as RenderBox?;
      if (box != null) {
        left += box.size.width;
      }
      if (i != 0 || widget.selectedIndex > 0) {
        left += widget.tabSpacing;
      }
    }
    final RenderBox? selectedBox = textKeys[widget.selectedIndex]
        .currentContext
        ?.findRenderObject() as RenderBox?;
    if (selectedBox != null) {
      final tabWidth = selectedBox.size.width;
      setState(() {
        lineLeft = left + (tabWidth - widget.lineWidth) / 2;
      });
    }
  }

  double _getTotalWidth() {
    double total = 0;
    for (int i = 0; i < widget.tabs.length; i++) {
      final RenderBox? box =
          textKeys[i].currentContext?.findRenderObject() as RenderBox?;
      if (box != null) {
        total += box.size.width;
      }
      if (i != widget.tabs.length - 1) {
        total += widget.tabSpacing;
      }
    }
    return total == 0 ? 200 : total;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: widget.padding,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // tab 行
          Row(
            mainAxisSize: MainAxisSize.min,
            children: List.generate(widget.tabs.length, (index) {
              return Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  GestureDetector(
                    onTap: () => widget.onTabTap(index),
                    child: Text(
                      widget.tabs[index],
                      key: textKeys[index],
                      style: widget.selectedIndex == index
                          ? (widget.selectedTextStyle ??
                              TextStyle(
                                color: widget.selectedColor,
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              ))
                          : (widget.unselectedTextStyle ??
                              TextStyle(
                                color: widget.unselectedColor,
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              )),
                    ),
                  ),
                  if (index != widget.tabs.length - 1)
                    SizedBox(width: widget.tabSpacing),
                ],
              );
            }),
          ),
          SizedBox(height: widget.verticalSpacing),
          // 下划线
          SizedBox(
            height: widget.lineHeight,
            width: _getTotalWidth(),
            child: Stack(
              children: [
                AnimatedPositioned(
                  duration: widget.lineDuration,
                  curve: widget.lineCurve,
                  left: lineLeft,
                  child: Container(
                    width: widget.lineWidth,
                    height: widget.lineHeight,
                    decoration: BoxDecoration(
                      color: widget.lineColor,
                      borderRadius: BorderRadius.circular(widget.lineRadius),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
